﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data.OracleClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml;
using DevExpress.Xpo;
using LprMiddleWare.DAL;
using LprMiddleWare.Model;
using LprMiddleWare.ServiceReference1;
using LprMiddleWare.Services;

namespace LprMiddleWare
{
    class UploadService
    {
        private const int MaxFileSize = 300 * 1024;
        private readonly Action<string> _uilogger;
        private XmlDocument _xmlTemplate;
        private ConcurrentBag<LicensePlate> _licensePlates
            = new ConcurrentBag<LicensePlate>();

        private Thread _thread;
        private Services.IUploader _uploader;
        private NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

        public UploadService(Action<string> Logger)
        {
            _uilogger = Logger;
            _xmlTemplate = new XmlDocument();
            _xmlTemplate.Load("UploadTemplate.xml");

            var service = new dyService();
            service.Url = Settings.LoadDefault().WeiZhangDataUrl;

            _uploader = service;

        }


        private Tuple<string, string> ParseResult(string resultXml)
        {
            const string resultTag = "<result>";
            const string messageTag = "<message>";
            const string messageEndTag = "</message>";
            var i1 = resultXml.IndexOf(resultTag, StringComparison.Ordinal);
            var i2 = resultXml.IndexOf(messageTag, StringComparison.Ordinal);
            var i3 = resultXml.IndexOf(messageEndTag, StringComparison.Ordinal);
            var res = resultXml.Substring(i1 + resultTag.Length, 1);
            var msg = resultXml.Substring(i2 + messageTag.Length, i3 - i2 - messageTag.Length);
            return new Tuple<string, string>(res, msg);
        }

        public bool Upload(LicensePlate licensePlate)
        {
            if (_licensePlates.Count < 100)
            {
                _licensePlates.Add(licensePlate);
            }
            else
            {
                LogMessage("超速违章数据上传队列已满，请检查远端上传web服务是否工作正常!!");
            }

            return true;

        }


        private void LogMessage(string msg)
        {
            if (_uilogger != null)
            {
                _uilogger(msg);
            }
        }

        private string GetAbsolutePath(string subPath)
        {
            return Path.Combine(Settings.LoadDefault().TargetDirectory, subPath);
        }
    }
}
